<?php

abstract class Indexer_Service_ResultProxy implements Iterator
{
    protected $result = array();
    protected $currentIndex = 0;
    protected $limit  = 0;
    protected $offset = 0;
    
    public function __construct(&$nativeResult)
    {
        $this->result =& $nativeResult;
    }
      
    /**
     * Sets the limit of maximum number of results returned, 
     * 0 == unlimited.
     * Throws exception if passed parameter is not a positive integer.
     *
     * @param integer $limit
     * @throws Indexer_Exception
     */
    public function setLimit($limit)
    {
        if (is_numeric($limit) && $limit >= 0) {
            $this->limit = (int)$limit;
        } else {
            throw new Indexer_Exception('Limit must be a positive integer value');
        }
    }
    
    /**
     * Set the offset from which to start returning results,
     * 0 == start at first result.
     * Throws exception if passed parameter is not a positive integer.
     *
     * @param integer $offset
     * @throws Indexer_Exception
     */    
    public function setOffset($offset)
    {
        if (is_numeric($offset) && $offset >= 0) {
            $this->currentIndex = $this->offset = (int)$offset;
        } else {
            throw new Indexer_Exception('Offset must be a positive integer value');
        }
    }
    
    /************** Functions to implement Iterator interface ************/
    
    public function next()
    {
        $this->currentIndex++;
    }
    
    public function valid()
    {
        if ($this->limit == 0) {
            return isset($this->result[$this->currentIndex]);
        } else {
            return isset($this->result[$this->currentIndex]) && ($this->currentIndex - $this->offset) < $this->limit;
        }
    }
    
    public function current()
    {
        /* @TODO add check if 'uri' is included in result */
        $doc = new Indexer_Document($this->result[$this->currentIndex]['uri']);
        foreach($this->result[$this->currentIndex] as $fieldName => $fieldValue) {
            $doc->setField($fieldName, $fieldValue);                
        }
        
        return $doc;
    }
    
    public function key()
    {
        return $this->currentIndex;
    }
    
    public function rewind()
    {
        $this->currentIndex = $this->offset;
    }

}